package cn.chowx.myjfinal.common;

import java.util.HashMap;
import java.util.Map;

import cn.chowx.myjfinal.help.PageFilterHelp;
import cn.chowx.myjfinal.help.PageHelp;
import cn.chowx.myjfinal.util.JsonUtil;

import com.google.common.base.Strings;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * 基础 controller 类
 * @author zcqshine
 *
 */
public class BaseController extends Controller {
	protected PageHelp pageHelp;
	
	/**
	 * 获取页面传来的分页、搜索信息,设置到 {@link PageHelp} 属性
	 */
	protected void setPageHelp(){
		int pageNumber = getParaToInt(("page"),1);
		int pageSize = getParaToInt(("rows"),10);
		long nd = getParaToLong("nd");
		String sidx = getPara("sidx");
		String sord = getPara(("sord"),"ACS");
		boolean search = getParaToBoolean("_search");
		
		String filters = getPara("filters");
		PageHelp ph = new PageHelp();
		if(!Strings.isNullOrEmpty(filters)){
			PageFilterHelp filter = JsonUtil.readValue(filters, PageFilterHelp.class);
			ph.setFilter(filter);
		}
		
		ph.setNd(nd);
		ph.setPageNum(pageNumber);
		ph.setRows(pageSize);
		ph.setSearch(search);
		ph.setSord(sord);
		ph.setSidx(sidx);
		this.pageHelp = ph;
	}
	
	/**
	 * 返回分页 json 格式的数据到页面
	 * @param page 分页数据
	 */
	protected void renderJsonData(Page<Record> page){
		Map<String,Object> root = new HashMap<>();
		root.put("total", page.getTotalPage());
		root.put("page", page.getPageNumber());
		root.put("records", page.getTotalRow());
		root.put("rows", page.getList());
		renderJson(JsonKit.toJson(root));
	}
	
	/**
	 * 重写getPara方法,去除值两边的空格
	 */
	@Override
	public String getPara(String name) {
		return getRequest().getParameter(name) == null? null : getRequest().getParameter(name).trim();
	}
}
